All files / controllers PipelineStagesController.js

0% Statements 0/104
0% Branches 0/60
0% Functions 0/5
0% Lines 0/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * Pipeline Stages Controller
 * Manages pipeline stages for tenant (admin can create/edit/delete)
 * Users can only move conversations between stages
 */
 
const BaseController = require('./BaseController');
const { pool } = require('../config/database');
const { logger } = require('../config/logger');
 
class PipelineStagesController extends BaseController {
  /**
   * Get all pipeline stages for tenant
   * GET /api/admin/pipeline-stages
   */
  static async getStages(req, res) {
    try {
      const tenantId = req.tenantId || req.user.tenantId;
 
      if (!tenantId) {
        return res.status(400).json({
          success: false,
          message: 'Tenant ID not found'
        });
      }
 
      const [stages] = await pool.execute(`
        SELECT id, stage_key, stage_name, stage_color, stage_icon, stage_order, is_default, active
        FROM pipeline_stages
        WHERE tenant_id = ?
        ORDER BY stage_order ASC
      `, [tenantId]);
 
      return res.json({
        success: true,
        data: stages
      });
    } catch (error) {
      logger.error('Error getting pipeline stages', {
        error: error.message,
        stack: error.stack
      });
 
      return res.status(500).json({
        success: false,
        message: 'Failed to load pipeline stages'
      });
    }
  }
 
  /**
   * Create new pipeline stage
   * POST /api/admin/pipeline-stages
   */
  static async createStage(req, res) {
    try {
      const tenantId = req.tenantId || req.user.tenantId;
      const { stage_key, stage_name, stage_color, stage_icon, stage_order } = req.body;
 
      if (!tenantId) {
        return res.status(400).json({
          success: false,
          message: 'Tenant ID not found'
        });
      }
 
      if (!stage_key || !stage_name) {
        return res.status(400).json({
          success: false,
          message: 'Stage key and name are required'
        });
      }
 
      // Check if stage key already exists
      const [existing] = await pool.execute(`
        SELECT id FROM pipeline_stages 
        WHERE tenant_id = ? AND stage_key = ?
      `, [tenantId, stage_key]);
 
      if (existing.length > 0) {
        return res.status(400).json({
          success: false,
          message: 'Stage key already exists'
        });
      }
 
      // Get next order if not provided
      let order = stage_order;
      if (!order) {
        const [maxOrder] = await pool.execute(`
          SELECT COALESCE(MAX(stage_order), 0) + 1 as next_order
          FROM pipeline_stages
          WHERE tenant_id = ?
        `, [tenantId]);
        order = maxOrder[0].next_order;
      }
 
      // Insert new stage
      const [result] = await pool.execute(`
        INSERT INTO pipeline_stages (tenant_id, stage_key, stage_name, stage_color, stage_icon, stage_order)
        VALUES (?, ?, ?, ?, ?, ?)
      `, [tenantId, stage_key, stage_name, stage_color || '#6b7280', stage_icon || 'fas fa-circle', order]);
 
      // Get the created stage
      const [newStage] = await pool.execute(`
        SELECT id, stage_key, stage_name, stage_color, stage_icon, stage_order, is_default, active
        FROM pipeline_stages
        WHERE id = ?
      `, [result.insertId]);
 
      // Emit to all users in tenant
      const io = req.app.get('io');
      if (io) {
        io.to(`TENANT:${tenantId}`).emit('pipeline-stage-created', {
          stage: newStage[0]
        });
      }
 
      return res.json({
        success: true,
        data: newStage[0],
        message: 'Pipeline stage created successfully'
      });
    } catch (error) {
      logger.error('Error creating pipeline stage', {
        error: error.message,
        stack: error.stack
      });
 
      return res.status(500).json({
        success: false,
        message: 'Failed to create pipeline stage'
      });
    }
  }
 
  /**
   * Update pipeline stage
   * PUT /api/admin/pipeline-stages/:id
   */
  static async updateStage(req, res) {
    try {
      const tenantId = req.tenantId || req.user.tenantId;
      const stageId = req.params.id;
      const { stage_name, stage_color, stage_icon, stage_order } = req.body;
 
      if (!tenantId) {
        return res.status(400).json({
          success: false,
          message: 'Tenant ID not found'
        });
      }
 
      // Check if stage exists and belongs to tenant
      const [existing] = await pool.execute(`
        SELECT id, is_default FROM pipeline_stages 
        WHERE id = ? AND tenant_id = ?
      `, [stageId, tenantId]);
 
      if (existing.length === 0) {
        return res.status(404).json({
          success: false,
          message: 'Pipeline stage not found'
        });
      }
 
      // Build update query
      const updates = [];
      const values = [];
 
      if (stage_name) {
        updates.push('stage_name = ?');
        values.push(stage_name);
      }
      if (stage_color) {
        updates.push('stage_color = ?');
        values.push(stage_color);
      }
      if (stage_icon) {
        updates.push('stage_icon = ?');
        values.push(stage_icon);
      }
      if (stage_order !== undefined) {
        updates.push('stage_order = ?');
        values.push(stage_order);
      }
 
      if (updates.length === 0) {
        return res.status(400).json({
          success: false,
          message: 'No fields to update'
        });
      }
 
      values.push(stageId, tenantId);
 
      await pool.execute(`
        UPDATE pipeline_stages 
        SET ${updates.join(', ')}, updated_at = NOW()
        WHERE id = ? AND tenant_id = ?
      `, values);
 
      // Get updated stage
      const [updatedStage] = await pool.execute(`
        SELECT id, stage_key, stage_name, stage_color, stage_icon, stage_order, is_default, active
        FROM pipeline_stages
        WHERE id = ?
      `, [stageId]);
 
      // Emit to all users in tenant
      const io = req.app.get('io');
      if (io) {
        io.to(`TENANT:${tenantId}`).emit('pipeline-stage-updated', {
          stage: updatedStage[0]
        });
      }
 
      return res.json({
        success: true,
        data: updatedStage[0],
        message: 'Pipeline stage updated successfully'
      });
    } catch (error) {
      logger.error('Error updating pipeline stage', {
        error: error.message,
        stack: error.stack
      });
 
      return res.status(500).json({
        success: false,
        message: 'Failed to update pipeline stage'
      });
    }
  }
 
  /**
   * Delete pipeline stage
   * DELETE /api/admin/pipeline-stages/:id
   */
  static async deleteStage(req, res) {
    try {
      const tenantId = req.tenantId || req.user.tenantId;
      const stageId = req.params.id;
 
      if (!tenantId) {
        return res.status(400).json({
          success: false,
          message: 'Tenant ID not found'
        });
      }
 
      // Check if stage exists and belongs to tenant
      const [existing] = await pool.execute(`
        SELECT id, stage_key, is_default FROM pipeline_stages 
        WHERE id = ? AND tenant_id = ?
      `, [stageId, tenantId]);
 
      if (existing.length === 0) {
        return res.status(404).json({
          success: false,
          message: 'Pipeline stage not found'
        });
      }
 
      // Don't allow deleting default stages
      if (existing[0].is_default) {
        return res.status(400).json({
          success: false,
          message: 'Cannot delete default pipeline stage'
        });
      }
 
      // Check if stage has conversations
      const [conversations] = await pool.execute(`
        SELECT COUNT(*) as count FROM whatsapp_cloud_conversations 
        WHERE tenant_id = ? AND stage_id = ?
      `, [tenantId, existing[0].stage_key]);
 
      if (conversations[0].count > 0) {
        // Move conversations to 'unassigned' before deleting the stage
        await pool.execute(`
          UPDATE whatsapp_cloud_conversations
          SET stage_id = 'unassigned', updated_at = NOW()
          WHERE tenant_id = ? AND stage_id = ?
        `, [tenantId, existing[0].stage_key]);
      }
 
      // Delete stage
      await pool.execute(`
        DELETE FROM pipeline_stages 
        WHERE id = ? AND tenant_id = ?
      `, [stageId, tenantId]);
 
      // Emit to all users in tenant
      const io = req.app.get('io');
      if (io) {
        io.to(`TENANT:${tenantId}`).emit('pipeline-stage-deleted', {
          stageId: parseInt(stageId),
          stageKey: existing[0].stage_key
        });
      }
 
      return res.json({
        success: true,
        message: 'Pipeline stage deleted successfully'
      });
    } catch (error) {
      logger.error('Error deleting pipeline stage', {
        error: error.message,
        stack: error.stack
      });
 
      return res.status(500).json({
        success: false,
        message: 'Failed to delete pipeline stage'
      });
    }
  }
 
  /**
   * Reorder pipeline stages
   * PUT /api/admin/pipeline-stages/reorder
   */
  static async reorderStages(req, res) {
    try {
      const tenantId = req.tenantId || req.user.tenantId;
      const { stages } = req.body; // Array of {id, order}
 
      if (!tenantId) {
        return res.status(400).json({
          success: false,
          message: 'Tenant ID not found'
        });
      }
 
      if (!Array.isArray(stages)) {
        return res.status(400).json({
          success: false,
          message: 'Stages array is required'
        });
      }
 
      // Update order for each stage
      for (const stage of stages) {
        await pool.execute(`
          UPDATE pipeline_stages 
          SET stage_order = ?, updated_at = NOW()
          WHERE id = ? AND tenant_id = ?
        `, [stage.order, stage.id, tenantId]);
      }
 
      // Get updated stages
      const [updatedStages] = await pool.execute(`
        SELECT id, stage_key, stage_name, stage_color, stage_icon, stage_order, is_default, active
        FROM pipeline_stages
        WHERE tenant_id = ?
        ORDER BY stage_order ASC
      `, [tenantId]);
 
      // Emit to all users in tenant
      const io = req.app.get('io');
      if (io) {
        io.to(`TENANT:${tenantId}`).emit('pipeline-stages-reordered', {
          stages: updatedStages
        });
      }
 
      return res.json({
        success: true,
        data: updatedStages,
        message: 'Pipeline stages reordered successfully'
      });
    } catch (error) {
      logger.error('Error reordering pipeline stages', {
        error: error.message,
        stack: error.stack
      });
 
      return res.status(500).json({
        success: false,
        message: 'Failed to reorder pipeline stages'
      });
    }
  }
}
 
module.exports = PipelineStagesController;